#!/usr/bin/python
# -*- coding: utf-8 -*-

from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
from requestProcessor import DbRequestProcessor
import json
import os
import time
import urllib
import urlparse

class WebDbHandler (BaseHTTPRequestHandler):

	def do_GET(self):
		if self.path.endswith("?"):
			self.path = self.path[:-1]
		
		try:
			#### SPECIAL TREATMENT ####
			if self.path.startswith("/db"):
				self._processDbRequest()
			elif self.path == "/manifest.json":
				manifest = self._generateManifest()
				toWrite = json.dumps(manifest)
				self.send_response(200)
				self.send_header("Content-type", "application/json")
				self.end_headers()
				self.wfile.write(toWrite)
			#### NORMAL TREATMENT ####
			else:
				if self.path == "/":
					self.path = "/index.html"
				elif self.path == "/samples/":
					self.path = "/samples/index.html"
				f = open(os.getcwd() + self.path, 'rb') # binary mode!!!
				self.send_response(200)
				self._addContentType()
				self.end_headers()
				
				self.wfile.write(f.read())
				self.wfile.flush()
				f.close()
				
		except IOError:
			self.send_error(404, "File not found")
	
	def _processDbRequest(self):
		params = self.__getParams()
		requestObj = json.loads(params["r"])
		try:
			toReturn = self.requestProcessor.process(requestObj)
			self.send_response(200)
			self.send_header("Content-type", "application/json")
			self.end_headers()
			self.wfile.write(json.dumps(toReturn))
		except KeyError:
			self.send_error(400, "Bad Request")
			
	def __getParams(self):
		url = urlparse.urlparse(self.path)
		urlQuery = urllib.unquote(url.query)
		params = dict([part.split('=', 1) for part in urlQuery.split('&')])
		print params
		return params

	def _generateManifest(self):
		manifest = {}
		manifest["betaManifestVersion"] = 1
		
		manifest["entries"] = []
		manifest["entries"].append({ "url": "/", "redirect": "index.html" })
		manifest["entries"].append({ "url": ".", "redirect": "index.html" })
		lastModify = -1
		for dirname, dirnames, filenames in os.walk('.'):
#			print dirname, dirnames, filenames
			for filename in filenames:
				filenameWithPath = os.path.join(dirname, filename)
				modify = os.path.getmtime(filenameWithPath)
				if modify > lastModify:
					lastModify = modify
				if filenameWithPath.find(".svn") == -1 and filenameWithPath.find("samples") == -1:
					entry = {}
					entry["url"] = filenameWithPath.replace("\\", "/").replace("./", "")
					manifest["entries"].append(entry)
		manifest["version"] = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(lastModify))
		return manifest
	
	def _addContentType(self):
		if self.path.endswith(".html"):
			self.send_header("Content-type", "text/html")
		elif self.path.endswith(".js"):
			self.send_header("Content-type", "text/javascript")
		elif self.path.endswith(".css"):
			self.send_header("Content-type", "text/css")
		elif self.path.endswith(".png"):
			self.send_header("Content-type", "image/png")
		elif self.path.endswith(".gif"):
			self.send_header("Content-type", "image/gif")
		elif self.path.endswith(".manifest"): # HTML 5
			self.send_header("Content-type", "text/cache-manifest")


def main(port = 80):
	WebDbHandler.requestProcessor = DbRequestProcessor()
	try:
		print "WebDB server is running on localhost on port", port
		server = HTTPServer(('', port), WebDbHandler)
		server.serve_forever()
	except KeyboardInterrupt:
		server.socket.close()

if __name__ == "__main__":
	import sys
	os.chdir(os.path.join(os.path.dirname(__file__), "../client"))
	if len(sys.argv) > 1:
		port = int(sys.argv[1])
		main(port)
	else:
		main()
